import { MessageBox } from 'element-ui'

const Fn = {

  /**
     * @desc 函数防抖
     * @param func 函数
     * @param wait 延迟执行毫秒数
     * @param immediate true 表立即执行，false 表非立即执行
     */
  Debounce: (func, wait, immediate) => {
    let timeout
    wait = wait || 500
    immediate = immediate || true

    return function() {
      const context = this
      const args = arguments

      if (timeout) clearTimeout(timeout)
      if (immediate) {
        var callNow = !timeout
        timeout = setTimeout(() => {
          timeout = null
        }, wait)
        if (callNow) func.apply(context, args)
      } else {
        timeout = setTimeout(function() {
          func.apply(context, args)
        }, wait)
      }
    }
  },

  /**
     * 函数节流
     * @param fn
     * @param interval
     * @returns {Function}
     * @constructor
     */
  Throttle: (fn, t) => {
    let last
    let timer
    const interval = t || 500
    return function() {
      const args = arguments
      const now = +new Date()
      if (last && now - last < interval) {
        clearTimeout(timer)
        timer = setTimeout(() => {
          last = now
          // console.log("实际执行函数（" + interval + "）：" + typeof fn)
          fn.apply(this, args)
        }, interval)
      } else {
        last = now
        // console.log("实际执行函数（" + interval + "）：" + typeof fn)
        fn.apply(this, args)
      }
    }
  },

  // 用于包装需要弹出框确认的函数执行
  Confirm: (fn, msg) => {
    return function() {
      msg = msg || '确定？'
      MessageBox.confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const args = arguments
        fn.apply(this, args)
      }).catch(() => {

      })
    }
  },

  // 用于包装需要弹出框确认的函数执行
  Prompt: (fn, msg) => {
    return function() {
      msg = msg || '确定？'
      this.$prompt(msg, '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        const args = [value]
        fn.apply(this, args)
      }).catch(() => {

      })
    }
  }

}

export default Fn
